package com.easylinkin.linkappapi.roster.service.impl;
import cn.hutool.core.util.IdcardUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.easylinkin.linkappapi.common.service.CommonService;
import com.easylinkin.linkappapi.common.utils.DateUtil;
import com.easylinkin.linkappapi.common.utils.StringUtil;
import com.easylinkin.linkappapi.config.dao.SysDictItemMapper;
import com.easylinkin.linkappapi.config.dao.SysDictMapper;
import com.easylinkin.linkappapi.config.entity.SysDict;
import com.easylinkin.linkappapi.config.entity.SysDictItem;
import com.easylinkin.linkappapi.lobar.dto.excel.ExcelResultDTO;
import com.easylinkin.linkappapi.lobar.dto.excel.ExcelResultDetailDTO;
import com.easylinkin.linkappapi.roster.dto.LinkappRosterPersonnelDTO;
import com.easylinkin.linkappapi.roster.dto.RosterTypeEnum;
import com.easylinkin.linkappapi.roster.entity.LaborTeam;
import com.easylinkin.linkappapi.roster.entity.RailLinkappRosterPersonnel;
import com.easylinkin.linkappapi.roster.mapper.LaborTeamMapper;
import com.easylinkin.linkappapi.roster.mapper.LinkappRosterPersonnelMapper;
import com.easylinkin.linkappapi.roster.service.ILaborTeamService;
import com.easylinkin.linkappapi.roster.service.ILinkappRosterPersonnelService;
import com.easylinkin.linkappapi.roster.vo.LinkappRosterPersonnelVO;
import com.easylinkin.linkappapi.security.context.LinkappUserContextProducer;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;

/**
 * 人员花名册服务实现类
 * @author lyk
 * @date 2025/6/10 下午 4:52
 */
@Service
@Slf4j
public class LinkappRosterPersonnelServiceImpl extends ServiceImpl<LinkappRosterPersonnelMapper, RailLinkappRosterPersonnel>  implements ILinkappRosterPersonnelService {
    @Resource
    private CommonService commonService;
    @Resource
    private SysDictMapper sysDictMapper;
    @Resource
    private SysDictItemMapper sysDictItemMapper;
    @Autowired
    private LinkappUserContextProducer linkappUserContextProducer;
    @Autowired
    private LaborTeamMapper teamMapper;
    @Override
    public IPage<LinkappRosterPersonnelVO> selectPage(Page page, LinkappRosterPersonnelDTO linkappRosterPersonnelDTO) {
        linkappRosterPersonnelDTO.setTenantId(linkappUserContextProducer.getNotNullCurrent().getTenantId());
        return baseMapper.selectPage(page,linkappRosterPersonnelDTO);
    }

    @Override
    public boolean managAndStaffSave(RailLinkappRosterPersonnel requestModel) {
        commonService.setCreateAndModifyInfo(requestModel);
        requestModel.setTenantId(linkappUserContextProducer.getNotNullCurrent().getTenantId());
        //默认在岗位
        requestModel.setWorkStatus(1);
        validParamRequired(requestModel);
        return save(requestModel);
    }

    @Override
    public boolean protectAndSpecialSave(Map<String, Object> parameters) {
        String id = Objects.toString(parameters.get("id"), "");
        String rosterType = Objects.toString(parameters.get("rosterType"), "");
        Assert.isTrue(StringUtils.isNotBlank(rosterType), "人员类型不能为空");
        RailLinkappRosterPersonnel railLinkappRosterPersonnel = baseMapper.selectById(Long.valueOf(id));
        Assert.notNull(railLinkappRosterPersonnel, "人员记录不存在");
        rosterTypeAndProtectSpecial(railLinkappRosterPersonnel,rosterType,parameters);
        return updateById(railLinkappRosterPersonnel);
    }

    @Override
    public boolean rosterEdit(LinkappRosterPersonnelDTO linkappRosterPersonnelDTO) {
        RailLinkappRosterPersonnel railLinkappRosterPersonnel = baseMapper.selectById(linkappRosterPersonnelDTO.getId());
        Assert.notNull(railLinkappRosterPersonnel, "人员记录不存在");
        linkappRosterPersonnelDTO.setRosterType(railLinkappRosterPersonnel.getRosterType());
        if (!Objects.isNull(linkappRosterPersonnelDTO.getStartTime())){
            boolean b = DateUtil.compareTimes(LocalDateTime.parse(DateUtil.getYYYYMMDDHHMMSSDate(linkappRosterPersonnelDTO.getStartTime()), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")), LocalDateTime.now());
            if (b){
                linkappRosterPersonnelDTO.setWorkStatus(1);
            }
        }else{
            linkappRosterPersonnelDTO.setStartTime(null);
        }
        if (!Objects.isNull(linkappRosterPersonnelDTO.getEndTime())){
            boolean b = DateUtil.compareTimes(LocalDateTime.parse(DateUtil.getYYYYMMDDHHMMSSDate(linkappRosterPersonnelDTO.getEndTime()), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")), LocalDateTime.now());
            if (b){
                linkappRosterPersonnelDTO.setWorkStatus(0);
            }
        }else{
            linkappRosterPersonnelDTO.setEndTime(null);
        }
        QueryWrapper<RailLinkappRosterPersonnel> objectQueryWrapper = new QueryWrapper<>();
        objectQueryWrapper.eq("id",linkappRosterPersonnelDTO.getId());
        baseMapper.update(linkappRosterPersonnelDTO,objectQueryWrapper);
        return true;
    }

    @Override
    public boolean rosterDel(String ids) {
        List<String> strings = Arrays.asList(ids.split(","));
        return retBool(baseMapper.deleteBatchIds(strings));
    }

    @Override
    public boolean rosterBack(String ids, String time,String flag) throws Exception {
        time = URLDecoder.decode(time, String.valueOf(StandardCharsets.UTF_8));
        ids = URLDecoder.decode(ids, String.valueOf(StandardCharsets.UTF_8));
        if ("0".equals(flag)){
            //退场
        List<String> strings = Arrays.asList(ids.split(","));
        List<RailLinkappRosterPersonnel> railLinkappRosterPersonnels = baseMapper.selectBatchIds(strings);
        for (RailLinkappRosterPersonnel rosterPersonnel:railLinkappRosterPersonnels){
            rosterPersonnel.setEndTime(DateUtil.getDateFromYYYYMMDDHHmmss(time));
            rosterPersonnel.setWorkStatus(0);
            commonService.setModifyInfo(rosterPersonnel);
            baseMapper.updateById(rosterPersonnel);

        }  }else if("1".equals(flag)){
            //入场
            List<String> strings = Arrays.asList(ids.split(","));
            List<RailLinkappRosterPersonnel> railLinkappRosterPersonnels = baseMapper.selectBatchIds(strings);
            for (RailLinkappRosterPersonnel rosterPersonnel:railLinkappRosterPersonnels){
                rosterPersonnel.setStartTime(DateUtil.getDateFromYYYYMMDDHHmmss(time));
                rosterPersonnel.setWorkStatus(1);
                rosterPersonnel.setEndTime(null);
                commonService.setModifyInfo(rosterPersonnel);
                baseMapper.updateById(rosterPersonnel);
            }
        }
        return true;
    }

    @Override
    public boolean rosterAuths(String ids, String gatePermis) {
        List<String> strings = Arrays.asList(ids.split(","));
        List<RailLinkappRosterPersonnel> railLinkappRosterPersonnels = baseMapper.selectBatchIds(strings);
        String[] gatePermis_arrs = gatePermis.split(",");
        Map<String, String> gatePermisMap = new HashMap<>();
        for (String gateId:gatePermis_arrs){
            if (!StringUtils.isEmpty(gateId)){
                gatePermisMap.put(gateId,gateId);
            }
        }
        for (RailLinkappRosterPersonnel rosterPersonnel:railLinkappRosterPersonnels){
             if (!Objects.isNull(rosterPersonnel)){
                 String gate  = rosterPersonnel.getGatePermis();
                 if (StringUtils.isEmpty(gate)){
                     List<String> gates = new ArrayList<>();
                     for (Map.Entry<String, String> entry : gatePermisMap.entrySet()) {
                         String key = entry.getKey();
                         gates.add(key);
                     }
                     rosterPersonnel.setGatePermis(String.join(",",gate));
                     commonService.setModifyInfo(rosterPersonnel);
                     boolean b = updateById(rosterPersonnel);
                     if (!b){
                         return false;
                     }
                 }else{
                     List<String> gates = new ArrayList<>(Arrays.asList(gate.split(",")));
                     for (Map.Entry<String, String> entry : gatePermisMap.entrySet()) {
                         String key = entry.getKey();
                         //String value = entry.getValue();
                        if (!gates.contains(key)){
                            gates.add(key);
                        }
                     }
                     rosterPersonnel.setGatePermis(String.join(",",gates));
                     commonService.setModifyInfo(rosterPersonnel);
                     boolean b = updateById(rosterPersonnel);
                     if (!b){
                         return false;
                     }
                 }
             }
        }
        return true;
    }

    /*@Override
    public boolean rosterExec(String ids, String startTime) {
        List<String> strings = Arrays.asList(ids.split(","));
        List<RailLinkappRosterPersonnel> railLinkappRosterPersonnels = baseMapper.selectBatchIds(strings);
        for (RailLinkappRosterPersonnel rosterPersonnel:railLinkappRosterPersonnels){
            rosterPersonnel.setEndTime(DateUtil.getDateFromYYYYMMDDHHmmss(startTime));
            rosterPersonnel.setWorkStatus(1);
            commonService.setModifyInfo(rosterPersonnel);
            boolean b = updateById(rosterPersonnel);
            if (!b){
                return false;
            }
        }
        return true;
    }*/

    /**
     * 导入前置校验
     * @param file
     * @param tenantId
     * @return
     */
    @Override
    public ExcelResultDTO importRosterExcelCheck(MultipartFile file, String tenantId) throws IOException {
        ExcelResultDTO res = new ExcelResultDTO();
        List<ExcelResultDetailDTO> excelResultDetailDTOS = new ArrayList<ExcelResultDetailDTO>();
        Integer success = 0;
        Integer fail = 0;
        Integer index = 0;
        InputStream inputStream = file.getInputStream();
        Workbook workbook = WorkbookFactory.create(inputStream);
        log.debug("共有 " + workbook.getNumberOfSheets() + " Sheets : ");
        //循环工作簿
        for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
            Sheet sheet = workbook.getSheetAt(i);
            Date createTime = new Date();
            int rows = sheet.getPhysicalNumberOfRows();
            for (int row = 2; row < rows; row++) {
                // 读取左上端单元格
                //index = row;
                Row row_n = sheet.getRow(row);
                if (row_n != null) {
                    ExcelResultDetailDTO excelResultDetailDTO = null;
                    /**
                     *    String keyValue = "姓名(必填*):realName,性别(必填*):sex,工种(必填*):workType,"
                     *                     + "身份证号码(必填*):idsNo,联系电话(必填*):linkPhone,劳务队伍(必填*):laborTeam";
                     */
                    index++;
                    String realName = getValue(row_n.getCell(0)); // 姓名
                    String sex = getValue(row_n.getCell(1)); // 性别
                    String workType = getValue(row_n.getCell(2));// 工种
                    String idsNo = getValue(row_n.getCell(3)); // 身份证号码
                    String linkPhone = getValue(row_n.getCell(4)); // 联系电话
                    String laborTeam = getValue(row_n.getCell(5)); // 劳务队伍
                    if (StringUtils.isEmpty(realName)){
                        excelResultDetailDTO = new ExcelResultDetailDTO();
                        excelResultDetailDTO.setNo(i);
                        excelResultDetailDTO.setName("姓名不能为空");
                        excelResultDetailDTO.setType(1);
                        excelResultDetailDTO.setDetail("姓名不能为空");
                        excelResultDetailDTOS.add(excelResultDetailDTO);
                        fail++;
                        continue;
                    }
                    if (StringUtils.isEmpty(sex)){
                        excelResultDetailDTO = new ExcelResultDetailDTO();
                        excelResultDetailDTO.setNo(i);
                        excelResultDetailDTO.setName("性别不能为空");
                        excelResultDetailDTO.setType(1);
                        excelResultDetailDTO.setDetail("性别不能为空");
                        excelResultDetailDTOS.add(excelResultDetailDTO);
                        fail++;
                        continue;
                    }
                    if (!(sex.equals("男") || sex.equals("女"))){
                        excelResultDetailDTO = new ExcelResultDetailDTO();
                        excelResultDetailDTO.setNo(i);
                        excelResultDetailDTO.setName("性别格式错误");
                        excelResultDetailDTO.setType(1);
                        excelResultDetailDTO.setDetail("性别格式错误");
                        excelResultDetailDTOS.add(excelResultDetailDTO);
                        fail++;
                        continue;
                    }
                    if (StringUtils.isEmpty(workType)){
                        excelResultDetailDTO = new ExcelResultDetailDTO();
                        excelResultDetailDTO.setNo(i);
                        excelResultDetailDTO.setName("工种不能为空");
                        excelResultDetailDTO.setType(1);
                        excelResultDetailDTO.setDetail("工种不能为空");
                        excelResultDetailDTOS.add(excelResultDetailDTO);
                        fail++;
                        continue;
                    }
                    if (StringUtils.isEmpty(idsNo)){
                        excelResultDetailDTO = new ExcelResultDetailDTO();
                        excelResultDetailDTO.setNo(i);
                        excelResultDetailDTO.setName("身份证号码不能为空");
                        excelResultDetailDTO.setType(1);
                        excelResultDetailDTO.setDetail("身份证号码不能为空");
                        excelResultDetailDTOS.add(excelResultDetailDTO);
                        fail++;
                        continue;
                    }
                    if (StringUtils.isEmpty(linkPhone)){
                        excelResultDetailDTO = new ExcelResultDetailDTO();
                        excelResultDetailDTO.setNo(i);
                        excelResultDetailDTO.setName("联系方式不能为空");
                        excelResultDetailDTO.setType(1);
                        excelResultDetailDTO.setDetail("联系方式不能为空");
                        excelResultDetailDTOS.add(excelResultDetailDTO);
                        fail++;
                        continue;
                    }
                    if (StringUtils.isEmpty(laborTeam)){
                        excelResultDetailDTO = new ExcelResultDetailDTO();
                        excelResultDetailDTO.setNo(i);
                        excelResultDetailDTO.setName("劳务队伍不能为空");
                        excelResultDetailDTO.setType(1);
                        excelResultDetailDTO.setDetail("劳务队伍不能为空");
                        excelResultDetailDTOS.add(excelResultDetailDTO);
                        fail++;
                        continue;
                    }
                    LaborTeam team = null;
                    //查询劳务队伍
                    QueryWrapper<LaborTeam> objectQueryWrapper = new QueryWrapper<>();
                    objectQueryWrapper.eq("labor_team_name_",laborTeam);
                    List<LaborTeam>  LaborTeams =  teamMapper.selectList(objectQueryWrapper);
                    if (!Objects.isNull(LaborTeams)){
                        if (LaborTeams.size()>0){
                            team = LaborTeams.get(0);
                        }
                    }
                    if (Objects.isNull(team)){
                        excelResultDetailDTO = new ExcelResultDetailDTO();
                        excelResultDetailDTO.setNo(i);
                        excelResultDetailDTO.setName("劳务队伍不存在");
                        excelResultDetailDTO.setType(1);
                        excelResultDetailDTO.setDetail("劳务队伍不存在");
                        excelResultDetailDTOS.add(excelResultDetailDTO);
                        fail++;
                        continue;
                    }
                    //获取工种类型
                    // 如果缓存中没有，则从数据库查询
                    QueryWrapper queryWrapper = new QueryWrapper();
                    queryWrapper.eq("dict_code_", "work_type");
                    SysDict sysDict = sysDictMapper.selectOne(queryWrapper);
                    if (Objects.isNull(sysDict)){
                        excelResultDetailDTO = new ExcelResultDetailDTO();
                        excelResultDetailDTO.setNo(i);
                        excelResultDetailDTO.setName(realName+"的工种类型没有配置");
                        excelResultDetailDTO.setType(1);
                        excelResultDetailDTO.setDetail(realName+"的工种类型没有配置");
                        excelResultDetailDTOS.add(excelResultDetailDTO);
                        fail++;
                        continue;
                    }
                    QueryWrapper itemQueryWrapper = new QueryWrapper();
                    itemQueryWrapper.eq("dict_id_", sysDict.getId());
                    itemQueryWrapper.eq("item_text_", workType);
                    SysDictItem sysDictItem = sysDictItemMapper.selectOne(itemQueryWrapper);
                    if (Objects.isNull(sysDictItem)){
                        excelResultDetailDTO = new ExcelResultDetailDTO();
                        excelResultDetailDTO.setNo(i);
                        excelResultDetailDTO.setName(realName+"的工种在系统内不存在");
                        excelResultDetailDTO.setType(1);
                        excelResultDetailDTO.setDetail(realName+"的工种在系统内不存在");
                        excelResultDetailDTOS.add(excelResultDetailDTO);
                        fail++;
                        continue;
                    }
                    QueryWrapper rosterQueryWrapper = new QueryWrapper();
                    rosterQueryWrapper.eq("ids_no",idsNo);
                    rosterQueryWrapper.eq("tenant_id", tenantId);
                    RailLinkappRosterPersonnel railLinkappRosterPersonnel = baseMapper.selectOne(rosterQueryWrapper);
                    if (!Objects.isNull(railLinkappRosterPersonnel)){
                        excelResultDetailDTO = new ExcelResultDetailDTO();
                        excelResultDetailDTO.setNo(i);
                        excelResultDetailDTO.setName(realName+"在系内已经存在");
                        excelResultDetailDTO.setType(1);
                        excelResultDetailDTO.setDetail(realName+"在系内已经存在");
                        excelResultDetailDTOS.add(excelResultDetailDTO);
                        fail++;
                        continue;
                    }
                    String birth = IdcardUtil.getBirthByIdCard(idsNo);
                    RailLinkappRosterPersonnel rosterPersonnel = new RailLinkappRosterPersonnel();
                    //租户id
                    rosterPersonnel.setTenantId(tenantId);
                    commonService.setCreateAndModifyInfo(rosterPersonnel);
                    rosterPersonnel.setIdsNo(idsNo);
                    rosterPersonnel.setRealName(realName);
                    rosterPersonnel.setWorkType(sysDictItem.getItemValue());
                    rosterPersonnel.setLinkPhone(linkPhone);
                    rosterPersonnel.setSex(sex);
                    rosterPersonnel.setRosterType(RosterTypeEnum.CONTRACT_WORKERS.getValue());
                    rosterPersonnel.setWorkStatus(1);
                    rosterPersonnel.setBirthdayDate(birth);
                    rosterPersonnel.setLaborTeam(String.valueOf(team.getId()));
                    if (Objects.isNull(excelResultDetailDTO)){
                        //成功
                        success++;
                    }else{
                        //失败
                        excelResultDetailDTOS.add(excelResultDetailDTO);
                        fail++;
                    }

                }
            }
        }
        res.setSum(index);
        res.setFail(fail);
        res.setSuccess(success);
        res.setExcelResultDetailDTOS(excelResultDetailDTOS);
        return res;
    }

    @Override
    public List<LinkappRosterPersonnelVO> selecList(LinkappRosterPersonnelDTO requestModel) {
        requestModel.setTenantId(linkappUserContextProducer.getNotNullCurrent().getTenantId());
        return baseMapper.selectPage(requestModel);
    }

    @Override
    public ExcelResultDTO importRosterExcel(MultipartFile file, String tenantId) throws IOException {
        ExcelResultDTO res = new ExcelResultDTO();
        List<ExcelResultDetailDTO> excelResultDetailDTOS = new ArrayList<ExcelResultDetailDTO>();
        Integer success = 0;
        Integer fail = 0;
        Integer index = 0;
        InputStream inputStream = file.getInputStream();
        Workbook workbook = WorkbookFactory.create(inputStream);
        log.debug("共有 " + workbook.getNumberOfSheets() + " Sheets : ");
        //循环工作簿
        for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
            Sheet sheet = workbook.getSheetAt(i);
            Date createTime = new Date();
            int rows = sheet.getPhysicalNumberOfRows();
            for (int row = 2; row < rows; row++) {
                // 读取左上端单元格
                //index = row;
                Row row_n = sheet.getRow(row);
                if (row_n != null) {
                    ExcelResultDetailDTO excelResultDetailDTO = null;
                    /**
                     *    String keyValue = "姓名(必填*):realName,性别(必填*):sex,工种(必填*):workType,"
                     *                     + "身份证号码(必填*):idsNo,联系电话(必填*):linkPhone,劳务队伍(必填*):laborTeam";
                     */
                    index++;
                    String realName = getValue(row_n.getCell(0)); // 姓名
                    String sex = getValue(row_n.getCell(1)); // 性别
                    String workType = getValue(row_n.getCell(2));// 工种
                    String idsNo = getValue(row_n.getCell(3)); // 身份证号码
                    String linkPhone = getValue(row_n.getCell(4)); // 联系电话
                    String laborTeam = getValue(row_n.getCell(5)); // 劳务队伍
                    if (StringUtils.isEmpty(realName)){
                        excelResultDetailDTO = new ExcelResultDetailDTO();
                        excelResultDetailDTO.setNo(i);
                        excelResultDetailDTO.setName("姓名不能为空");
                        excelResultDetailDTO.setType(1);
                        excelResultDetailDTO.setDetail("姓名不能为空");
                        continue;
                    }
                    if (StringUtils.isEmpty(sex)){
                        excelResultDetailDTO = new ExcelResultDetailDTO();
                        excelResultDetailDTO.setNo(i);
                        excelResultDetailDTO.setName("性别不能为空");
                        excelResultDetailDTO.setType(1);
                        excelResultDetailDTO.setDetail("性别不能为空");
                        continue;
                    }
                    if (!(sex.equals("男") || sex.equals("女"))){
                        excelResultDetailDTO = new ExcelResultDetailDTO();
                        excelResultDetailDTO.setNo(i);
                        excelResultDetailDTO.setName("性别格式错误");
                        excelResultDetailDTO.setType(1);
                        excelResultDetailDTO.setDetail("性别格式错误");
                        continue;
                    }
                    if (StringUtils.isEmpty(workType)){
                        excelResultDetailDTO = new ExcelResultDetailDTO();
                        excelResultDetailDTO.setNo(i);
                        excelResultDetailDTO.setName("工种不能为空");
                        excelResultDetailDTO.setType(1);
                        excelResultDetailDTO.setDetail("工种不能为空");
                        continue;
                    }
                    if (StringUtils.isEmpty(idsNo)){
                        excelResultDetailDTO = new ExcelResultDetailDTO();
                        excelResultDetailDTO.setNo(i);
                        excelResultDetailDTO.setName("身份证号码不能为空");
                        excelResultDetailDTO.setType(1);
                        excelResultDetailDTO.setDetail("身份证号码不能为空");
                        continue;
                    }
                    if (StringUtils.isEmpty(linkPhone)){
                        excelResultDetailDTO = new ExcelResultDetailDTO();
                        excelResultDetailDTO.setNo(i);
                        excelResultDetailDTO.setName("联系方式不能为空");
                        excelResultDetailDTO.setType(1);
                        excelResultDetailDTO.setDetail("联系方式不能为空");
                        continue;
                    }
                    if (StringUtils.isEmpty(laborTeam)){
                        excelResultDetailDTO = new ExcelResultDetailDTO();
                        excelResultDetailDTO.setNo(i);
                        excelResultDetailDTO.setName("劳务队伍不能为空");
                        excelResultDetailDTO.setType(1);
                        excelResultDetailDTO.setDetail("劳务队伍不能为空");
                        continue;
                    }
                    LaborTeam team = null;
                    //查询劳务队伍
                    QueryWrapper<LaborTeam> objectQueryWrapper = new QueryWrapper<>();
                    objectQueryWrapper.eq("labor_team_name_",laborTeam);
                    List<LaborTeam>  LaborTeams =  teamMapper.selectList(objectQueryWrapper);
                    if (!Objects.isNull(LaborTeams)){
                        if (LaborTeams.size()>0){
                            team = LaborTeams.get(0);
                        }
                    }
                    if (Objects.isNull(team)){
                        excelResultDetailDTO = new ExcelResultDetailDTO();
                        excelResultDetailDTO.setNo(i);
                        excelResultDetailDTO.setName("劳务队伍不存在");
                        excelResultDetailDTO.setType(1);
                        excelResultDetailDTO.setDetail("劳务队伍不存在");
                        continue;
                    }
                    //获取工种类型
                    // 如果缓存中没有，则从数据库查询
                    QueryWrapper queryWrapper = new QueryWrapper();
                    queryWrapper.eq("dict_code_", "work_type");
                    SysDict sysDict = sysDictMapper.selectOne(queryWrapper);
                    if (Objects.isNull(sysDict)){
                        excelResultDetailDTO = new ExcelResultDetailDTO();
                        excelResultDetailDTO.setNo(i);
                        excelResultDetailDTO.setName(realName+"的工种类型没有配置");
                        excelResultDetailDTO.setType(1);
                        excelResultDetailDTO.setDetail(realName+"的工种类型没有配置");
                        continue;
                    }
                    QueryWrapper itemQueryWrapper = new QueryWrapper();
                    itemQueryWrapper.eq("dict_id_", sysDict.getId());
                    itemQueryWrapper.eq("item_text_", workType);
                    SysDictItem sysDictItem = sysDictItemMapper.selectOne(itemQueryWrapper);
                    if (Objects.isNull(sysDictItem)){
                        excelResultDetailDTO = new ExcelResultDetailDTO();
                        excelResultDetailDTO.setNo(i);
                        excelResultDetailDTO.setName(realName+"的工种在系统内不存在");
                        excelResultDetailDTO.setType(1);
                        excelResultDetailDTO.setDetail(realName+"的工种在系统内不存在");
                        continue;
                    }
                    QueryWrapper rosterQueryWrapper = new QueryWrapper();
                    rosterQueryWrapper.eq("ids_no",idsNo);
                    rosterQueryWrapper.eq("tenant_id", tenantId);
                    RailLinkappRosterPersonnel railLinkappRosterPersonnel = baseMapper.selectOne(rosterQueryWrapper);
                    if (!Objects.isNull(railLinkappRosterPersonnel)){
                        excelResultDetailDTO = new ExcelResultDetailDTO();
                        excelResultDetailDTO.setNo(i);
                        excelResultDetailDTO.setName(realName+"在系内已经存在");
                        excelResultDetailDTO.setType(1);
                        excelResultDetailDTO.setDetail(realName+"在系内已经存在");
                        continue;
                    }
                    String birth = IdcardUtil.getBirthByIdCard(idsNo);
                    RailLinkappRosterPersonnel rosterPersonnel = new RailLinkappRosterPersonnel();
                    //租户id
                    rosterPersonnel.setTenantId(tenantId);
                    commonService.setCreateAndModifyInfo(rosterPersonnel);
                    rosterPersonnel.setIdsNo(idsNo);
                    rosterPersonnel.setRealName(realName);
                    rosterPersonnel.setWorkType(sysDictItem.getItemValue());
                    rosterPersonnel.setLinkPhone(linkPhone);
                    rosterPersonnel.setSex(sex);
                    rosterPersonnel.setRosterType(RosterTypeEnum.CONTRACT_WORKERS.getValue());
                    rosterPersonnel.setWorkStatus(1);
                    rosterPersonnel.setBirthdayDate(birth);
                    rosterPersonnel.setLaborTeam(String.valueOf(team.getId()));
                    boolean save = save(rosterPersonnel);
                    if (!save){
                        excelResultDetailDTO = new ExcelResultDetailDTO();
                        excelResultDetailDTO.setNo(i);
                        excelResultDetailDTO.setName(realName+"数据库保存失败");
                        excelResultDetailDTO.setType(1);
                        excelResultDetailDTO.setDetail(realName+"数据库保存失败");
                        continue;
                    }
                    if (Objects.isNull(excelResultDetailDTO)){
                        //成功
                        success++;
                    }else{
                        //失败
                        excelResultDetailDTOS.add(excelResultDetailDTO);
                        fail++;
                    }

                }
            }
        }
        res.setSum(index);
        res.setFail(fail);
        res.setSuccess(success);
        res.setExcelResultDetailDTOS(excelResultDetailDTOS);
        return res;
    }

    @Override
    public boolean rosterByUpdateType(String ids, String rosterType) {
        List<String> strings = Arrays.asList(ids.split(","));
        List<RailLinkappRosterPersonnel> railLinkappRosterPersonnels = baseMapper.selectBatchIds(strings);
        for (RailLinkappRosterPersonnel rosterPersonnel:railLinkappRosterPersonnels){
            String rosterType_n = rosterPersonnel.getRosterType();
            List<String> rosterType_now = new ArrayList<>();
            String[] strings1 = rosterType_n.split(",");
           for (String rt:strings1){
               if (!StringUtils.isEmpty(rt)){
                   if (!rt.equals(rosterType)){
                       rosterType_now.add(rt);
                       rosterPersonnel.setRosterType(String.join(",",rosterType_now));
                       commonService.setModifyInfo(rosterPersonnel);
                       break;
                   }
               }
           }
        }
        return updateBatchById(railLinkappRosterPersonnels);
    }

    private String getValue(Cell xSSFCell) {

        if (null == xSSFCell) {

            return "";
        }
        try {

            return String.valueOf(xSSFCell.getStringCellValue());

        } catch (Exception ex) {

        }

        return "";
    }
    public void rosterTypeAndProtectSpecial(RailLinkappRosterPersonnel railLinkappRosterPersonnel,String rosterType,Map<String, Object> parameters){
        if (rosterType.equals(RosterTypeEnum.PROTECTIVE_OFFICER.getValue())){
            //防护员
            String protectType = Objects.toString(parameters.get("protectType"), "");
            String protectLssuingAuth = Objects.toString(parameters.get("protectLssuingAuth"), "");
            String protectAuthBookDate = Objects.toString(parameters.get("protectAuthBookDate"), "");
            String protectAuthBookContent = Objects.toString(parameters.get("protectAuthBookContent"), "");
            Assert.isTrue(StringUtils.isNotBlank(protectType), "防护员类型不能为空");
            Assert.isTrue(StringUtils.isNotBlank(protectLssuingAuth), "发证机构不能为空");
            Assert.isTrue(StringUtils.isNotBlank(protectAuthBookDate), "证书有效期不能为空");
            Assert.isTrue(StringUtils.isNotBlank(protectAuthBookContent), "证书内容页不能为空");

            String protectHealthStatus = Objects.toString(parameters.get("protectHealthStatus"), "");
            String protectHealthAuthContent = Objects.toString(parameters.get("protectHealthAuthContent"), "");
            //类型赋值
            List<String> objects = new ArrayList<>();
            objects.add(railLinkappRosterPersonnel.getRosterType());
            objects.add(rosterType);
            railLinkappRosterPersonnel.setRosterType(String.join(",",objects));
            //必填项
            railLinkappRosterPersonnel.setProtectType(protectType);
            railLinkappRosterPersonnel.setProtectLssuingAuth(protectLssuingAuth);
            railLinkappRosterPersonnel.setProtectAuthBookDate(protectAuthBookDate);
            railLinkappRosterPersonnel.setProtectAuthBookContent(protectAuthBookContent);
            if (!StringUtils.isEmpty(protectHealthStatus)){
                railLinkappRosterPersonnel.setProtectHealthStatus(protectHealthStatus);
            }
            if (!StringUtils.isEmpty(protectHealthAuthContent)){
                railLinkappRosterPersonnel.setProtectHealthAuthContent(protectHealthAuthContent);
            }
        }
        if (rosterType.equals(RosterTypeEnum.SPECIAL_OPERATION.getValue())){
            //特种作业人员
            //String specialAuthBookType = Objects.toString(parameters.get("specialAuthBookType"), "");
            String specialAuthBookJson = Objects.toString(parameters.get("specialAuthBookJson"), "");
            Assert.isTrue(StringUtils.isNotBlank(specialAuthBookJson), "特种作业人员证书不能为空");
            List<String> objects = new ArrayList<>();
            objects.add(railLinkappRosterPersonnel.getRosterType());
            objects.add(rosterType);
            railLinkappRosterPersonnel.setRosterType(String.join(",",objects));
            railLinkappRosterPersonnel.setSpecialAuthBookJson(specialAuthBookJson);
        }
    }

    /**
     * 校验参数
     */
    private void validParamRequired(RailLinkappRosterPersonnel linkappRosterPersonnel) {

        Assert.notNull(linkappRosterPersonnel, "参数为空");
        Assert.notNull(linkappRosterPersonnel.getRosterType(), "人员类型不能为空");
        if (linkappRosterPersonnel.getRosterType().contains(RosterTypeEnum.MANAGER.getValue()) || linkappRosterPersonnel.getRosterType().contains(RosterTypeEnum.CONTRACT_WORKERS.getValue()) ){
            Assert.isTrue(StringUtils.isNotBlank(linkappRosterPersonnel.getRealName()), "人员姓名不能为空");
            if (!StringUtils.isEmpty(linkappRosterPersonnel.getIdsNo())){
                String birth = IdcardUtil.getBirthByIdCard(linkappRosterPersonnel.getIdsNo());
                Integer sex = IdcardUtil.getGenderByIdCard(linkappRosterPersonnel.getIdsNo());
                String sex_s = (sex.equals(0)?"女":"男");
                linkappRosterPersonnel.setBirthdayDate(birth);
                linkappRosterPersonnel.setSex(sex_s);
            }
        }
    }
    @Override
    public SysDictItem getDict(String dictCode,String dictValue){
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("dict_code_", dictCode);
        SysDict sysDict = sysDictMapper.selectOne(queryWrapper);
        if (Objects.isNull(sysDict)){
           return null;
        }
        QueryWrapper itemQueryWrapper = new QueryWrapper();
        itemQueryWrapper.eq("dict_id_", sysDict.getId());
        itemQueryWrapper.eq("item_value_", dictValue);
        SysDictItem sysDictItem = sysDictItemMapper.selectOne(itemQueryWrapper);
        return sysDictItem;
    }

    /**
     * 特种人员证书封装
     * @param record
     */
    @Override
    public void specialAuthBookFz(IPage<LinkappRosterPersonnelVO> record) {
        // 计算90天前的日期
        LocalDate currentDate_now = LocalDate.now();
        if (record.getRecords().size()>0){
            for (LinkappRosterPersonnelVO rosterPersonnel:record.getRecords()){
                List<Map<String,String>> specialAuthBook = new ArrayList<>();
                List<Map<String,String>> specialAuthBookAj = new ArrayList<>();
               String  specialAuthBookJson_str =  rosterPersonnel.getSpecialAuthBookJson();
                specialAuthBookJson_str = Objects.toString(specialAuthBookJson_str,"");
                if (StringUtils.isEmpty(specialAuthBookJson_str) || specialAuthBookJson_str.equals("[]")){
                    rosterPersonnel.setSpecialAuthBook(specialAuthBook);
                    rosterPersonnel.setSpecialAuthBookAj(specialAuthBookAj);
                }else{
                Object json = com.alibaba.fastjson.JSONObject.toJSON(specialAuthBookJson_str);
                com.alibaba.fastjson.JSONArray parseArray = com.alibaba.fastjson.JSONArray.parseArray(json.toString());
                List<Map> javaList = parseArray.toJavaList(Map.class);
                for (Map<String,String> map:javaList){
                    /**
                     * [{specialAuthBookType=2,
                     * specialAuthBookDate=2025-06-03~2025-07-23,
                     * specialAuthBookContent=https://jg-linkthings.oss-cn-hangzhou.aliyuncs.com/public/aep/test/picture/001.jpg}]
                     */

                    specialAuthBook.add(map);
                    String specialAuthBookDate = Objects.toString(map.get("specialAuthBookDate"), "");
                    if (!StringUtils.isEmpty(specialAuthBookDate)){
                        String[] split = specialAuthBookDate.split("~");
                        if (split.length == 2){
                            String endDate =  split[1];
                            Date parse = DateUtil.parse(endDate, DateUtil.DATE_TIME_FORMAT_DAY);
                            // 方法 1：使用 toInstant() 和系统默认时区（最常用）
                            LocalDate endDate_local = parse.toInstant()
                                    .atZone(ZoneId.systemDefault())
                                    .toLocalDate();
                            // 计算两个日期之间的天数差
                            long daysBetween = ChronoUnit.DAYS.between(currentDate_now ,endDate_local);

                            if (daysBetween <= 30) {
                                specialAuthBookAj.add(map);
                            }
                        }
                    }

                }
                    rosterPersonnel.setSpecialAuthBook(specialAuthBook);
                    rosterPersonnel.setSpecialAuthBookAj(specialAuthBookAj);
            }}
        }
    }


}
